<template>
	<div class="dzyb-wrapper page-wrapper">
		<!-- 订正预报 -->
		<!-- 导航栏 -->
		<navbar />

		<Map :config="MapConfig" @getMap="getMap" />
		<MapTool :map-tool="MapToolConfig" @getKey="getKey">
			<template
				v-for="item in mapToolsRows"
				v-slot:[item.key]
				:mapToolsRows="mapToolsRows"
			>
				<div
					:key="item.key"
					@click="clickHandler(item.key, item.active)"
					v-html="item.render"
				/>
			</template>
		</MapTool>
		<mapPopup
			:c-option="cOption"
			:c-x-axis="cXAxis"
			:pop-title="popTitle"
			:popup-type="popupType"
		></mapPopup>

		<div class="absolute bottom-0 left-0 z-1 invisible sm:visible">
			<Legend
				:default-option="legendConfig.defaultOption"
				:config="legendConfig.config"
			/>
		</div>
		<sidebar class="sidebar-container" />
		<!-- 日期范围 -->
		<time-period
			:start-time="product.startTime"
			:date="product.date"
			:moment="product.moment"
		></time-period>
		<product
			path="/dzyb"
			:modes-select="modesSelect"
			:hours-select="hoursSelect"
			@get-forecast="handleSearch"
			@change-period="changePeriod"
			@check-product="checkProduct"
			@site-search="searchSite"
			@make-product="makeProduct"
		/>
		<!-- 制作产品 -->
		<el-dialog
			center
			width="40%"
			title="产品制作"
			:visible="dialogVisible"
			:close-on-click-modal="false"
			:before-close="handleClose"
		>
			<el-form
				ref="productForm"
				label-width="6em"
				label-suffix=":"
				:model="product"
				:rules="productRules"
			>
				<el-form-item label="预报人员" prop="forecastUsr">
					<el-autocomplete
						placeholder="请输入预报人员"
						class="inline-input"
						value-key="label"
						v-model="product.forecastUsr"
						:fetch-suggestions="
							(queryString, cb) => {
								makerFilter(queryString, cb, 'fUsers');
							}
						"
					>
						<template slot-scope="{ item }">
							<div class="maker-label">{{ item.label }}</div>
						</template>
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="录入人员" prop="enteringUsr">
					<el-autocomplete
						placeholder="请输入录入人员"
						class="inline-input"
						value-key="label"
						v-model="product.enteringUsr"
						:fetch-suggestions="
							(queryString, cb) => {
								makerFilter(queryString, cb, 'eUsers');
							}
						"
					>
						<template slot-scope="{ item }">
							<div class="maker-label">{{ item.label }}</div>
						</template>
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="校验人员" prop="verifyUsr">
					<el-autocomplete
						placeholder="请输入校验人员"
						class="inline-input"
						value-key="label"
						v-model="product.verifyUsr"
						:fetch-suggestions="
							(queryString, cb) => {
								makerFilter(queryString, cb, 'vUsers');
							}
						"
					>
						<template slot-scope="{ item }">
							<div class="maker-label">{{ item.label }}</div>
						</template>
					</el-autocomplete>
				</el-form-item>
				<el-form-item label="签发单位" prop="department">
					<el-input v-model="product.department"></el-input>
				</el-form-item>
				<el-form-item style="text-align: center">
					<el-button type="primary" @click="submitProduct">
						生成产品
					</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
import Navbar from '@/components/Navbar'
import Sidebar from '@/components/Sidebar'
import Product from '@/components/Product'
import TimePeriod from '@/components/TimePeriod'

import {
	patterns,
	hours_d,
	product,
	proRules
} from '@/utils/constant.js'
import {
	getAction,
	postAction
} from '@/api/action'

import {
	module,
	legendConfig
} from '../dzyb/config'
import {
	MapConfig,
	ChartConfig,
	MapToolConfig,
	PopLayerConfig,
	BaseMapConfig
} from '../map.config'

import cnBorder from '../../assets/geoData/450400.json'

import {
	isInChina
} from '../../utils/mapUtils/isInChina'
import {
	requestPointData,
	formateData,
	renderChart
} from '../../utils/mapUtils/renderChart'
import 'ol/ol.css'
import 'weatherstar-switch/dist/switch.css'
import dayjs from 'dayjs'
import Map from '@automan-component/map'
import Legend from '@automan-component/legend'
import MapTool from '../../components/Map/mapTool'

import mapPopup from '../../components/Map/mapPopup'


import CuiteMap from '../../utils/map'

import {
	clear,
	measure,
	print
} from '@automan-component/maputils'

import cuiteFilter from '../../utils/mapUtils/filter'

export default {
	name: 'Dzyb',
	components: {
		Navbar,
		Sidebar,
		Product,
		TimePeriod,
		Map,
		MapTool,
		mapPopup,
		Legend
	},
	data() {
		return {
			urls: {
				getForecastData: '/api/correctForecast/getForecastData', // 雨量订正查询
				makeProduce: '/api/correctForecast/makeProduce', // 制作产品
				maker: '/api/makeUser/list', // 产品制作人数据查询
				isoband: '/api/correctForecast/getForecastData',//色斑图数据
			},
			modesSelect: patterns,
			hoursSelect: hours_d,
			productsSelect: product,
			dialogVisible: false,
			pageLoading: null,
			product: {
				pattern: '0', // 模式
				startTime: '8', // 起报
				date: dayjs().format('YYYY-MM-DD'),
				moment: '12', // 时效
				forecastUsr: '',
				enteringUsr: '',
				verifyUsr: '',
				department: '梧州市气象局',
			},
			productRules: proRules,
			maker: {
				fUsers: [],
				eUsers: [],
				vUsers: [],
			},
			MapConfig,
			MapToolConfig,
			legendConfig,
			date: dayjs().format('YYYY-MM-DD'),
			stationData: [],
			map: null,
			cuitemap: null,
			cuitefilter: null,
			mapToolsRows: [],
			layerGroup: [],
			mapdata: null,
			loading: false,
			chartOption: ChartConfig.options,
			popTitle: '',
			cOption: [],
			cXAxis: [],
			popupType: '',
		}
	},
	created() {
		this.combineRows()
	},
	methods: {
		// 雨量订正查询
		handleSearch(params) {
			this.pageLoading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			Object.assign(this.product, params);
			getAction(this.urls.getForecastData, params).then(res => {
				if (res.msg === '成功' && res.objects) {
					this.stationData = res['objects'];
					let sampleData = [];
					this.stationData.forEach(item => {
						item['timeValue'] = item['time' + (this.product.moment || 12)];
						sampleData.push([parseFloat(item['lon']), parseFloat(item['lat']), parseFloat(item['timeValue'])]);
						// if (this.product.moment == '24') {
						//   item['timeValue'] = item['time24'];
						// } else if (this.product.moment == '36') {
						//   item['timeValue'] = item['time36'];
						// } else if (this.product.moment == '48') {
						//   item['timeValue'] = item['time48'];
						// } else if (this.product.moment == '60') {
						//   item['timeValue'] = item['time60'];
						// } else if (this.product.moment == '72') {
						//   item['timeValue'] = item['time72'];
						// } else {
						//   item['timeValue'] = item['time12'];
						// }
					})
					this.cuitemap.addClusterFeatureLayer('rain', this.stationData);
					this.cuitemap.addClusterFeatureLayer('rainlabel', this.stationData);
					this.cuitemap.addIsoBandLayer('isoband', sampleData);
					this.pageLoading.close();
					//   console.log(this.stationData);
					(res.objects.length) || this.$message({
						message: '查询成功，但无数据',
						type: 'info',
					});
				}
			}).catch(err => {
				this.pageLoading.close()
			});
		},
		// 时效选择
		changePeriod(params) {
			this.product.moment = params.moment;
			console.log('时效', params.moment);
			const sampleData = [];
			this.stationData.forEach(item => {
				item['timeValue'] = item['time' + (this.product.moment || 12)];
				sampleData.push([parseFloat(item['lon']), parseFloat(item['lat']), parseFloat(item['timeValue'])]);
				// if (this.product.moment == '24') {
				//   item['timeValue'] = item['time24'];
				// } else if (this.product.moment == '36') {
				//   item['timeValue'] = item['time36'];
				// } else if (this.product.moment == '48') {
				//   item['timeValue'] = item['time48'];
				// } else if (this.product.moment == '60') {
				//   item['timeValue'] = item['time60'];
				// } else if (this.product.moment == '72') {
				//   item['timeValue'] = item['time72'];
				// } else {
				//   item['timeValue'] = item['time12'];
				// }
			})
			this.cuitemap.addClusterFeatureLayer('rain', this.stationData);
			this.cuitemap.addClusterFeatureLayer('rainlabel', this.stationData);
			this.cuitemap.addIsoBandLayer('isoband', sampleData);
		},
		// 产品选择
		checkProduct(val, item) {
			if (item['label'] == "暴雨规划") {
				this.cuitemap.getImageLayer('back').setVisible(val);
			} else if (item['label'] == "色斑图") {
				this.cuitemap.getLayer('isoband').setVisible(val);
			}
		},
		// 站点搜索
		searchSite(site) {
			// 经纬度为0的无法搜索
			if (site && site['longitude'] && site['latitude']) {
				site['lon'] = site['longitude'];
				site['lat'] = site['latitude'];
				this.cuitemap.addFeatureLayer('search', [site], true);
				this.cuitemap.fitToPoint(parseFloat(site['longitude']), parseFloat(site['latitude']))
			}
		},
		// 制作产品
		makeProduct(obj) {
			this.getMaker();
			this.dialogVisible = true;
			Object.assign(this.product, obj);
			// this.product.department = '梧州市气象局';
		},
		// 获取制作人
		getMaker() {
			getAction(this.urls.maker).then(res => {
				this.maker = { fUsers: [], eUsers: [], vUsers: [], };
				if (res.object && res.object.length) {
					const first = res.object[0]
					this.product.forecastUsr = first.forecastUsr;
					this.product.enteringUsr = first.enteringUsr;
					this.product.verifyUsr = first.verifyUsr;
					res.object.map((item) => {
						this.maker.fUsers.push({ label: item.forecastUsr, value: item.id })
						this.maker.eUsers.push({ label: item.enteringUsr, value: item.id })
						this.maker.vUsers.push({ label: item.verifyUsr, value: item.id })
					})
				}
			})
		},
		// 设置下拉列表
		makerFilter(queryString, cb, type) {
			let makers = this.maker[type];

			let results = queryString ? makers.filter(this.inputMakerFilter(queryString)) : makers;
			cb(results);
		},
		// 根据输入值筛选下拉列表
		inputMakerFilter(queryString) {
			return (item) => {
				return (item.label.toLowerCase().indexOf(queryString.toLowerCase()) !== -1);
			};
		},
		// 关闭弹窗
		handleClose() {
			this.dialogVisible = false;
			this.$refs.productForm.resetFields();
		},
		// 提交产品制作
		async submitProduct() {
			this.pageLoading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			// this.cuitemap.exportMap((base64) => {
			//   console.log(base64)
			// });
			let validate = false;
			this.$refs.productForm.validate((valid) => {
				validate = valid;
			})
			if (validate) {
				await postAction(this.urls.makeProduce, this.product).then(res => {
					console.log(res);
					if (res.msg === '成功') {
						this.$alert(`${res.object} 制作成功`, res.msg, {
							confirmButtonText: '确定',
							callback: action => {
								this.handleClose();
							}
						});
					}
				}).catch(err => {
					this.pageLoading.close();
				})
			}
			this.pageLoading.close();
		},
		getKey(key, active) {
			// 切换地图
			if (key === 'switch') this.changeMap(active)
		},
		// 获取map对象,初始化自定义map属性事件
		getMap(map) {
			// 获取view并fit
			this.cuitemap = new CuiteMap(map);
			this.cuitemap.addOverLayer();
			this.cuitefilter = new cuiteFilter(map);
			this.cuitemap.initBaseLayer(BaseMapConfig);

			this.cuitemap.initLayer('border', {
				fill_color: 'rgba(62,138,234,0.2)',
				stroke_color: 'rgba(62,138,234,1)',
				stroke_width: 2,
			});
			this.cuitemap.addGeoJSONLayer('border', cnBorder);

			this.cuitemap.initImageLayer('back', require('../dzyb/back.png'), [12259877.9732, 2573337.6502, 12448104.6774,
				2809470.4290
			]);
			this.cuitemap.initLayer('isoband');
			this.cuitemap.getLayer('isoband').setVisible(false);
			// this.cuitemap.getImageLayer('back').setVisible(false);

			this.cuitemap.initClusterLayer('rain', {
				image_url: require('../../assets/images/circle.png'),
				image_scale: 1
			}, (data) => {
				this.popupType = 'rain'
				this.popTitle = data.staionName;

				this.cXAxis = [];
				this.cOption = [];
				// 获取折线图x轴刻度
				for (const key in data) {
					// 匹配 time+数字的字段
					if (Object.hasOwnProperty.call(data, key) && /^time\d+$/i.test(key)) {
						this.cXAxis.push(+key.replace('time', ''));
					}
				}
				this.cXAxis.sort((a, b) => { return a - b });
				// 获取数据
				for (let idx = 0; idx < this.cXAxis.length; idx++) {
					const axis = this.cXAxis[idx];
					this.cOption.push(data['time' + axis]);
				}

				// this.cXAxis = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48, 51, 54, 57, 60, 63, 66, 69, 72];
				// this.cOption = [data['time3'], data['time12'], data['time24'], data['time36'], data['time48'], data['time60'], data[
				// 	'time72']];
			});
			this.cuitemap.initClusterLayer('rainlabel');


			this.cuitemap.initLayer('search', {
				image_url: require('../../assets/images/location.png'),
				image_scale: 0.5
			}, (data) => {
				this.popupType = 'search'
				this.popTitle = data.stationName;
				this.cOption = [data];
			});
		},
		combineRows() {
			MapToolConfig.content.forEach((content) => {
				const temp = []
				temp.push(...content.row)
				temp.forEach((item) => {
					this.mapToolsRows.push({
						key: item.key,
						render: item.render,
						zIndex: item.zIndex,
						active: false
					})
				})
			})
		},
		// 切换地图
		changeMap(active) {
			this.cuitemap.changeBaseLayer(active);
		},
		clickHandler(key, active) {
			switch (key) {
				case 'ranging':
					this.measureLine()
					break
				case 'surface':
					this.measurePolygon()
					break
				case 'clear':
					clear(this.cuitemap.map, 'lineAndArea', 'measureOverlay')
					break
				case 'download':
					print(this.cuitemap.map)
					break
				case 'rectangle':
					this.geomFilter('RectAngle');
					break
				case 'circle':
					this.geomFilter('Circle');
					break
				case 'polygon':
					this.geomFilter('Polygon');
					break
				case 'clean':
					this.geomFilter();
					break
			}
		},
		geomFilter(type) {
			if (!type) {
				this.cuitefilter.clearFilter();
				return;
			}
			this.cuitefilter.activateFilter(this.cuitemap.getLayer('rain'), type, (result, extent) => {
				this.pageLoading = this.$loading({
					lock: true,
					text: 'Loading',
					spinner: 'el-icon-loading',
					background: 'rgba(0, 0, 0, 0.7)'
				});
				setTimeout(() => {
					let point = this.cuitemap.getPiexlCoordinates([-776, 129]);
					if (result.length) {
						this.cuitemap.setOverlayerCoordinate(point);
					} else {
						this.$message.warning('选择范围内没有站点，请重新选择。')
						this.cuitemap.setOverlayerCoordinate([extent[0], (extent[1] + extent[3]) / 2]);
					}
					// this.cuitemap.setOverlayerCoordinate([extent[0], (extent[1] + extent[3]) / 2]);
					let data = [];
					result.forEach(_arr => {
						let arr = _arr && _arr.features ? _arr.features : [];
						arr.forEach(item => {
							data.push(item.getProperties())
						})
					})
					this.popupType = "edit";
					this.cOption = data;
				}, 30)
				this.pageLoading.close();
			}, (error) => {
				this.$message({
					message: '范围不能超过100平方公里！',
					type: 'warning'
				})
				this.pageLoading.close();
				return;
			});
		},
		measureLine() {
			measure(this.cuitemap.map, 'LineString')
		},
		measurePolygon() {
			measure(this.cuitemap.map, 'Polygon')
		}
	},
}
</script>

<style>
.ol-tooltip {
	position: relative;
	background: rgba(0, 0, 0, 0.5);
	border-radius: 4px;
	color: white;
	padding: 4px 8px;
	opacity: 0.7;
	white-space: nowrap;
	font-size: 12px;
}

.ol-tooltip-measure {
	opacity: 1;
	font-weight: bold;
}

.ol-tooltip-static {
	background-color: #ffcc33;
	color: black;
	border: 1px solid white;
}

.ol-tooltip-measure:before,
.ol-tooltip-static:before {
	border-top: 6px solid rgba(0, 0, 0, 0.5);
	border-right: 6px solid transparent;
	border-left: 6px solid transparent;
	content: "";
	position: absolute;
	bottom: -6px;
	margin-left: -7px;
	left: 50%;
}

.ol-tooltip-static:before {
	border-top-color: #ffcc33;
}

.row {
	width: 11.5rem;
	padding-left: 1rem;
	height: 2rem;
}

.rowTool {
	height: 2em;
	line-height: 2em;
	width: 7em;
	/* text-align: center; */
	cursor: pointer;
}

.rowTool:hover {
	background-color: #e0e0e0;
}

.checkbox {
	display: inline-block;
	margin-right: 0.5em;
}

.switch-small {
	width: 42px;
}

.pic {
	width: 1em;
	height: 1em;
	vertical-align: middle;
}

.spanText {
	vertical-align: middle;
	padding-left: 0.3rem;
}

.msgpic {
	width: 2rem;
	vertical-align: middle;
	margin-right: 1rem;
}

.msgspan {
	vertical-align: middle;
}

.vl-notify.vl-notify-msg {
	background-color: white;
	width: 12rem;
	height: 4rem;
	left: 53%;
	padding: 0;
	line-height: 4rem;
	color: black;
	font: 14px Helvetica Neue, Helvetica, PingFang SC, \5fae\8f6f\96c5\9ed1,
		Tahoma, Arial, sans-serif;
	padding-top: 1rem;
}

.sweet-modal .sweet-content {
	padding: 0;
}

.sweet-modal.is-alert .sweet-content {
	padding: 0;
}

.sweet-modal {
	width: 800px;
	height: 430px;
	max-width: 800px;
	overflow-y: hidden;
}

.sweet-modal-overlay {
	/* background-color: transparent; */
	/* top: 2.6rem;
    left: 2rem; */
	background-color: rgba(0, 0, 0, 0.3);
	/* opacity: 0.3; */
	position: absolute;
	height: 100%;
	width: 100%;
	z-index: 2;
}

.sweet-modal .sweet-box-actions .sweet-action-close:hover {
	background-color: #5252fb;
}

.sweet-modal .sweet-box-actions {
	top: 8px;
}

.infowindow {
	/* display: none; */
	width: 800px;
	height: 400px;
}

.infowindow-header {
	height: 100px;
	width: 100%;
}

.menu {
	width: 480px;
	height: 100px;
	margin-left: 120px;
}

.menu ul {
	list-style: none;
}

.menu div span {
	padding: 2px 8px;
	border: 1px solid #5252fb;
	display: inline-block;
	margin-top: 8px;
	border-radius: 6px;
	margin-left: 10px;
	font-size: 12px;
	cursor: pointer;
}

.active {
	background-color: #5252fb;
	color: #ffffff;
}

.infowindow-content {
	width: 100%;
	height: 320px;
}

.chart {
	width: 100%;
	height: 100%;
}

.mask {
	background-color: rgb(0, 0, 0);
	opacity: 0.5;
	position: absolute;
	width: 100%;
	height: 100%;
	z-index: 3;
	text-align: center;
}

.w-40 {
	width: 10em;
}

.leading-10 {
	line-height: 2.5em;
}

.text-base {
	font-size: 1em;
}

.px-8 {
	padding-left: 2em;
	padding-right: 2em;
}

.leading-10 {
	line-height: 2.5em;
}

.text-sm {
	font-size: 0.875em;
}

.w-4 {
	width: 1em;
}

.h-4 {
	height: 1em;
}
</style>

<style lang="scss">
.dzyb-wrapper {
	.el-autocomplete {
		width: 100%;
	}
}

#map {
	position: absolute;
	top: 0;
	width: 100%;
	height: 100%;
	overflow: hidden;
	#zoom {
		.zoom button {
			width: 20px !important;
			height: 20px !important;
		}
	}
}

.rowTool {
	height: 2em;
	line-height: 2em;
	width: 7em;
	text-align: left;
	cursor: pointer;
	.pic {
		margin-left: 1em;
		width: 1em;
		height: 1em;
		vertical-align: middle;
	}
	.spanText {
		vertical-align: middle;
		padding-left: 1em;
	}
	&:hover {
		background-color: #e0e0e0;
	}
}
</style>
